package com.android.dialnowsms;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.ContentValues;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.View;

class SMSSender implements Runnable, View.OnClickListener{
  private String url;
  private String response;
  private String phone_number;
  private String sms_message;
  private String error_message;
  private String service_url;
  private String username;
  private String password;
  private String sender_number;
  private String country_prefix;
  private SMSComposer composer_view;

  public SMSSender(SMSComposer smsComposer) {
    composer_view = smsComposer;
    SharedPreferences prefs = PreferenceManager
        .getDefaultSharedPreferences(composer_view);
    username = prefs.getString("username", "");
    password = prefs.getString("password", "");
    service_url = prefs.getString("service_url", "dialnow.com");
    sender_number = prefs.getString("sender_number", "");
    country_prefix = prefs.getString("country_prefix", "");
  }

  public void onClick(View v) {
    Thread thread = new Thread(this);
    thread.start();
    composer_view.log.setText("sending message...");
    composer_view.progress.setVisibility(View.VISIBLE);
  }

  public void run() {
    HttpClient httpClient = new DefaultHttpClient();

    phone_number = composer_view.number.getText() + "";
    // Phone number is like 0041791234123...
    if (phone_number.startsWith("00")) {
      phone_number = "+" + (composer_view.number.getText() + "").substring(2);
    // Phone number is like 0791231211...
    } else if (phone_number.startsWith("0")) {
      phone_number = country_prefix + (composer_view.number.getText() + "").substring(1);
    // Phone number is like 791231211...
    } else if  (! phone_number.startsWith("+") && !"".equals(country_prefix)) {
      phone_number = country_prefix + composer_view.number.getText();
    }

    sms_message = "" + composer_view.msg.getText();
    sms_message = sms_message.replace("\n", " ");
    sms_message = sms_message.replace(" ", "%20");
    url = "https://www." + service_url
    + "/myaccount/sendsms.php?username=" + username
    + "&password=" + password + "&from=" + sender_number
    + "&to=" + phone_number + "&text=" + sms_message;
    try {
      HttpGet httpGet = new HttpGet(url);
      ResponseHandler<String> rh = new BasicResponseHandler();
      response = httpClient.execute(httpGet, rh);
    } catch (ClientProtocolException e) {
      error_message = "error sending message ClientProtocolException";
    } catch (IOException e) {
      error_message = "error sending message IOException";
    }
    handler.sendEmptyMessage(0);
  }

  private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      composer_view.progress.setVisibility(View.GONE);

      if (error_message != null) {
        composer_view.log.setText(error_message);
      } else {
        response = response.replace("\n", " ");
        Boolean success = response.indexOf("success") > 0;
        if (success) {
        	// decode sms_message before showing and storing to local sms db
        	sms_message = sms_message.replace("%20", " ");
          composer_view.log.setText("SMS sent to " + phone_number);
          composer_view.sent_sms = phone_number + sms_message;
          ContentValues values = new ContentValues();
          values.put("address", phone_number);
          values.put("body", sms_message);
          composer_view.getContentResolver()
              .insert(Uri.parse("content://sms/sent"), values);
        } else {
          String error_msg = "There was an error sending SMS:\n";
          error_msg += "Service URL used: " + service_url + "\n";
          error_msg += "Username used: " + username + "\n";
          error_msg += "Sender nr used: " + sender_number + "\n";
          error_msg += "Error: ";
          Pattern pattern = Pattern
              .compile("<description>(.*?)</description>");
          Matcher matcher = pattern.matcher(response);
          if (matcher.find()) {
            composer_view.log.setText(error_msg + matcher.group(1));
          }
        }
      }
    }
  };
  
}
